//
//  LoginModel.m
//  ReactiveObjCDemo
//
//  Created by xth on 2017/12/9.
//  Copyright © 2017年 xth. All rights reserved.
//

#import "LoginModel.h"

@implementation LoginModel

- (UserModel *)account {
    if (!_account) {
        _account = [[UserModel alloc] init];
    }
    return _account;
}

- (instancetype)init {
    if (self = [super init]) {
        [self initialBind];
    }
    return self;
}

//初始化绑定
- (void)initialBind {
    
    //监听账号的属性改变，把他们聚合成一个信号
    _enableLoginSignal = [RACSignal combineLatest:@[RACObserve(self.account, account), RACObserve(self.account, pwd)] reduce:^id _Nullable (NSString *account, NSString *pwd){
        NSLog(@"account: %@, pwd: %@", account, pwd);
        return @(account.length && pwd.length);
    }];
    
    //处理登录逻辑
    _LoginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        NSLog(@"点击了登录");
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            //模拟网络延迟
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [subscriber sendNext:@"登录成功"];
                [subscriber sendCompleted];
            });
            
            return [RACDisposable disposableWithBlock:^{
                
            }];
        }];
    }];
    
    //监听登录产生的数据
    [[_LoginCommand.executing skip:1] subscribeNext:^(NSNumber * _Nullable x) {
        if ([x isEqualToNumber:@(YES)]) {
            NSLog(@"正在登录");
        } else {
            NSLog(@"登录成功");
        }
    }];
    
}

@end
